package handler

import (
	"context"
	"errors"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
	"log"
	"view-crawler-backend/internal/biz_error"
	"view-crawler-backend/internal/constant"
	"view-crawler-backend/internal/dto/req"
	"view-crawler-backend/internal/dto/resp"
	"view-crawler-backend/internal/service"
)

func QueryAllCategories(_ context.Context, c *app.RequestContext) {
	categories, err := service.QueryAllCategories()
	if err != nil {
		c.JSON(consts.StatusOK, resp.BuildErrorResponse(constant.DATABASE_OPERATE_ERROR))
		return
	}
	c.JSON(consts.StatusOK, resp.BuildSuccessResponse(categories))
}

func UpdateCategory(_ context.Context, c *app.RequestContext) {
	updateCategoryReq := &req.UpdateCategoryReq{}
	if err := c.BindAndValidate(updateCategoryReq); err != nil {
		log.Println(err)
		c.JSON(consts.StatusOK, resp.BuildErrorResponse(constant.INVALID_PARAM))
		return
	}

	if len(updateCategoryReq.NewAddCategoryList) == 0 && len(updateCategoryReq.NewDelCategoryList) == 0 {
		c.JSON(consts.StatusOK, resp.BuildErrorResponse(constant.INVALID_PARAM))
		return
	}
	categoryIdList, err := service.UpdateCategory(updateCategoryReq.NewAddCategoryList, updateCategoryReq.NewDelCategoryList)
	if err != nil {
		if errors.Is(err, biz_error.CategoryDelError) {
			c.JSON(consts.StatusOK, resp.BuildErrorResponse(constant.CATEGORY_DEL_ERROR))
			return
		}
		c.JSON(consts.StatusOK, resp.BuildErrorResponse(constant.DATABASE_OPERATE_ERROR))
		return
	}
	c.JSON(consts.StatusOK, resp.BuildSuccessResponse(categoryIdList))
}
